package com.qiyue.admin.auth.utils.jwt.utils;

import com.qiyue.admin.auth.configuration.JwtKeyConfiguration;
import com.qiyue.admin.auth.configuration.UserAuthConfig;
import com.qiyue.admin.auth.utils.jwt.exceotion.UserTokenException;
import com.qiyue.admin.auth.utils.model.IJWTInfo;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * Created with Intellij IDEA.
 * User : Yebinghuan
 * Created on 2018/2/10.
 * Description :
 *   用户认证
 */
@Configuration
public class UserAuthUtil {

    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private JwtKeyConfiguration jwtKeyConfiguration;



    /**
     *  从token中获取用户信息
     * @param token
     * @return
     * @throws Exception
     */
    public IJWTInfo getInfoFromToken(String token) throws Exception {
        try {
//            return JWTHelper.getInfoFromToken(token, userAuthConfig.getPubKeyByte());

            return JWTHelper.getInfoFromToken(token, jwtKeyConfiguration.getUserPubKey()); //因为是集中式所以就不需要去绕过去用userAuthConfig获取了
        }catch (ExpiredJwtException ex){
            throw new UserTokenException(UserTokenException.getExceptionModel(0));
        }catch (SignatureException ex){
            throw new UserTokenException(UserTokenException.getExceptionModel(1));
        }catch (IllegalArgumentException ex){
            throw new UserTokenException(UserTokenException.getExceptionModel(2));
        }
    }
}
